package cn.bytecollege.merchant.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter(filterName = "MerchantRegisterFilter",servletNames = "MerchantRegisterController")
public class MerchantRegisterFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req =(HttpServletRequest) request;
        HttpSession session = req.getSession();
        String msg = null;
        String method = req.getMethod();
        //获取表单数据
        String username= request.getParameter("username");
        String password = request.getParameter("password");
        String merchantParticulars = request.getParameter("merchantParticulars");
        if (method.equalsIgnoreCase("post")){ Pattern usernamePattern = Pattern.compile("\\w{5,12}");
            Matcher usernameMatcher = usernamePattern.matcher(username);
            if(!usernameMatcher.matches()){
                msg = "用户名只能包含数字、字母、下划线，长度为5-12位";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/admin/merchantRegister.jsp")
                        .forward(request, response);
                return;
            }

            Matcher passwordMatcher = usernamePattern.matcher(password);
            if(!passwordMatcher.matches()){
                msg = "密码只能包含数字、字母、下划线，长度为5-12位";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/admin/merchantRegister.jsp")
                        .forward(request, response);
                return;
            }
            if(merchantParticulars==null||merchantParticulars.equals("")) {
                msg = "请填写详细信息";
                request.setAttribute("msg", msg);
                request.getRequestDispatcher("/admin/merchantRegister.jsp")
                        .forward(request, response);
                return;
            }
            chain.doFilter(request,response);
            return;
        }
        chain.doFilter(request, response);
        }
    }

